package com.freecycle.sg.ui;

import java.util.HashMap;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.freecycle.sg.R;
import com.freecycle.sg.sqlite.Freebie.Freebies;
import com.freecycle.sg.sqlite.Freebie.ReferenceData;
import com.freecycle.sg.utils.Config;
import com.freecycle.sg.utils.NotifyingAsyncQueryHandler;
import com.freecycle.sg.utils.NotifyingAsyncQueryHandler.AsyncQueryListener;
import com.freecycle.sg.utils.UIUtils;

public class AddFreebieFragment extends Fragment implements AsyncQueryListener{

	private static final String TAG = "AddFreebieFragment";
	
	private NotifyingAsyncQueryHandler mHandler;
	
	private HashMap<String, String> mCategories;
	private Cursor mCursor;
	private ContentValues cv;
	
	private TextView category;
	private String categoryCode;
	private EditText title;
	private EditText name;
	private EditText description;
	private Button save;
	private Button discard;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mHandler = new NotifyingAsyncQueryHandler(getActivity()
				.getContentResolver(), this);
		setHasOptionsMenu(true);
		
		reloadFromArguments(getArguments());
	}
	
	public void reloadFromArguments(Bundle arguments) {
		// Abort currently running query if any
		mHandler.cancelOperation(FreebiesQuery._TOKEN);
		mHandler.cancelOperation(ReferenceQuery._TOKEN);
		
		// Load reference for categories
		mHandler.startQuery(ReferenceQuery._TOKEN, null,
				ReferenceData.CONTENT_URI, 
				ReferenceQuery.projection,
				ReferenceData.REF_DATA_TYPE + "=?", 
				new String[] { Config.REF_CATEGORIES },
				ReferenceData.DEFAULT_SORT);

		// Build intent based on loaded arguments
		final Intent intent = BaseActivity.fragmentArgumentsToIntent(arguments);
		final String action = intent.getAction();
		final Uri freebieUri = intent.getData();

		if (freebieUri == null) {
			return;
		}
		
		if (TextUtils.isEmpty(action)) {
			return;
		}
		
		Log.v(TAG, "action " + action);
		
		if (action.equals(Intent.ACTION_EDIT)) {
			final String freebieId = Freebies.getFreebieId(freebieUri);
			Log.v(TAG, "freebieId " + freebieId);
			if (!TextUtils.isEmpty(freebieId)) {
				// Load freebie from local database
				mHandler.startQuery(FreebiesQuery._TOKEN, null,
						Freebies.CONTENT_URI, 
						FreebiesQuery.projection,
						Freebies.FREEBIE_ID + "=?",
						new String[] { freebieId },
						Freebies.DEFAULT_SORT);
			}
		} else if (action.equals(Intent.ACTION_INSERT)) {
			cv = new ContentValues();
		}
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		final View view = inflater.inflate(R.layout.fragment_add_freebie, container, false);
		
		final DialogInterface.OnClickListener bathroomsListener = new OnClickListener() {
			public void onClick(DialogInterface dialog, int pos) {
				mCursor.moveToFirst();
				mCursor.move(pos);
		
				String text = mCursor.getString(ReferenceQuery.NAME);
				category.setText(text);
				categoryCode = mCursor.getString(ReferenceQuery.ABBREVIATION);

				dialog.dismiss();
			}
		};
		
		title = (EditText) view.findViewById(R.id.title);
		name = (EditText) view.findViewById(R.id.name);
		description = (EditText) view.findViewById(R.id.desciption);
		
		category = (TextView) view.findViewById(R.id.category);
		category.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// TODO display dialog to choose category
				AlertDialog.Builder builder = new  AlertDialog.Builder(getActivity());
				builder.setIcon(android.R.drawable.ic_dialog_info);
				builder.setTitle("Pick a category");
				builder.setCursor(mCursor, bathroomsListener, ReferenceData.NAME);
				builder.create().show();
			}
		});
		save = (Button) view.findViewById(R.id.save);
		save.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// TODO upload to server here
			}
		});
		discard = (Button) view.findViewById(R.id.discard);
		discard.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				getActivity().finish();
			}
		});
		
		
		
		return view;
	}
	
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.save_menu_items, menu);
		super.onCreateOptionsMenu(menu, inflater);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.menu_save) {
			uploadFreebie();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public void onQueryComplete(int token, Object cookie, Cursor c) {
		if (token == ReferenceQuery._TOKEN) {
			if (mCursor != null) {
				getActivity().stopManagingCursor(mCursor);
				mCursor = null;
			}
			
			mCursor = c;
			getActivity().startManagingCursor(mCursor);
			
			mCategories = new HashMap<String, String>();
			
			if (c.moveToFirst()) {
				do {
					String key = c.getString(ReferenceQuery.ABBREVIATION);
					String value = c.getString(ReferenceQuery.NAME);
					mCategories.put(key, value);
				} while (c.moveToNext());
			}
		} else if (token == FreebiesQuery._TOKEN) {
			getActivity().startManagingCursor(c);
			cv = UIUtils.buildFreebieCv(c);
			initData(c);
		} else {
			c.close();
		}
	}
	
	private void uploadFreebie(){
		
	}
	
	private void initData(Cursor c) {
		if (!c.moveToFirst()) {
			return;
		}
		
		
		
	}
	
	private interface FreebiesQuery {
		int _TOKEN = 0x231;

		String[] projection = { Freebies._ID, 
				Freebies.FREEBIE_ID,
				Freebies.ADDED, 
				Freebies.LATITUDE,
				Freebies.LONGITUDE, 
				Freebies.FORMATTED_ADDRESS, 
				Freebies.TITLE, 
				Freebies.DESCRIPTION,
				Freebies.CATEGORY,
				Freebies.PHONE,
				Freebies.NAME,
				};
		
		int FREEBIE_ID = 1;
		int ADDED = 2;
		int LATITUDE = 3;
		int LONGITUDE = 4;
		int FORMATTED_ADDRESS = 5;
		int TITLE = 6;
		int DESCRIPTION = 7;
		int CATEGORY = 8;
		int PHONE = 9;
		int NAME = 10;
	}
	
	private interface ReferenceQuery {
		int _TOKEN = 0x232;

		String[] projection = { 
				ReferenceData._ID,
				ReferenceData.REF_DATA_TYPE,
				ReferenceData.ABBREVIATION,
				ReferenceData.NAME,
				ReferenceData.MARKER_URL,
				};
		
		int REF_DATA_TYPE = 1;
		int ABBREVIATION = 2;
		int NAME = 3;
		int MARKER_URL = 4;
	}
	
}
